package com.qf.blog.filter;

import com.qf.blog.mybatis.MyBatisUtils;
import com.qf.blog.mybatis.SqlSessionThreadLocal;
import org.apache.ibatis.session.SqlSession;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

// 这个Filter主要是为创建SqlSession，所以需要连接那些要访问数据库的请求，
// 要访问数据库肯定要经过Servlet，所以这个Filter拦截Servlet
@WebFilter(filterName = "SqlSessionFilter", urlPatterns = {
        "/SystemUserServlet/*", "/PageServlet/*",
        "/IndexServlet/*", "/UserServlet/*",
        "/static/static/discuss-publish.html",
        "/invitataionServlet/*",
        "/commentServlet/*"
})
public class SqlSessionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        // 1.创建SqlSession
        SqlSession sqlSession = MyBatisUtils.getSqlSession();

        // 2.把SqlSession保存到Thredlocal中
        SqlSessionThreadLocal.set(sqlSession);

        try {
            // 3.放行
            filterChain.doFilter(servletRequest, servletResponse);

            // 4.事务提交
            sqlSession.commit(); // 调用commit操作会隐式关闭SqlSession
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
        }
    }
}
